package com.jeeplus.modules.web.web;

import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.audio.VideoUtil;
import com.jeeplus.common.utils.image.ImageUtil;
import com.jeeplus.common.utils.jwt.JwtTokenUtil;
import com.jeeplus.common.utils.redis.RedisKeys;
import com.jeeplus.common.utils.redis.RedisUtil;
import com.jeeplus.core.persistence.DataEntity;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.web.entity.*;
import com.jeeplus.modules.web.model.WxImageModel;
import com.jeeplus.modules.web.model.WxLoginModel;
import com.jeeplus.modules.web.model.WxLoginTypeEnum;
import com.jeeplus.modules.web.response.YjMahjongHallWaitersLoginResponse;
import com.jeeplus.modules.web.service.YjMahjongHallService;
import com.jeeplus.modules.web.service.YjMahjongHallWaitersService;
import com.jeeplus.modules.web.service.YjRoomCallsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 棋牌室服务生Controller
 * @author liangbing
 * @version 2021-03-11
 */
@Api(value = "YjMahjongHallWaitersController", description = "棋牌室服务生控制器")
@Controller
@RequestMapping(value = "${adminPath}/web/yjMahjongHallWaiters")
public class YjMahjongHallWaitersController extends BaseController {
    @Autowired
    private YjMahjongHallService yjMahjongHallService;

    @Autowired
    private YjMahjongHallWaitersService yjMahjongHallWaitersService;

    @Autowired
    private YjRoomCallsService yjRoomCallsService;

    @Autowired
    private RedisUtil redisUtil;

    private static final String CALL_PUSH_REDIS_PREFIX = "CallPush_";

    @ModelAttribute
    public YjMahjongHallWaiters get(@RequestParam(required=false) String id) {
        YjMahjongHallWaiters entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = yjMahjongHallWaitersService.get(id);
        }
        if (entity == null){
            entity = new YjMahjongHallWaiters();
        }
        return entity;
    }

    private static String PHONE_NUMBER = "phoneNumber";

    /**
     * 棋牌室服务生列表页面
     */
    @RequiresPermissions("web:yjMahjongHallWaiters:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/web/yjMahjongHallWaitersList";
    }

    /**
     * 棋牌室服务生列表数据
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallWaiters:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(YjMahjongHallWaiters yjMahjongHallWaiters, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<YjMahjongHallWaiters> page = yjMahjongHallWaitersService.findPage(new Page<YjMahjongHallWaiters>(request, response), yjMahjongHallWaiters);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑棋牌室服务生表单页面
     */
    @RequiresPermissions(value={"web:yjMahjongHallWaiters:view","web:yjMahjongHallWaiters:add","web:yjMahjongHallWaiters:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(YjMahjongHallWaiters yjMahjongHallWaiters, Model model) {
        model.addAttribute("yjMahjongHallWaiters", yjMahjongHallWaiters);
        if(StringUtils.isBlank(yjMahjongHallWaiters.getId())){//如果ID是空为添加
            model.addAttribute("isAdd", true);
            model.addAttribute("receiveCall", 1); //默认为接收语音推送
            model.addAttribute("workState", 1); //默认为工作中
        } else {
            model.addAttribute("receiveCall", new Integer(1).equals(yjMahjongHallWaiters.getReceiveCall()) ? 1 : 0);
            model.addAttribute("workState", new Integer(1).equals(yjMahjongHallWaiters.getWorkState()) ? 1 : 0);
        }

        return "modules/web/yjMahjongHallWaitersForm";
    }

    /**
     * 保存棋牌室服务生
     */
    @RequiresPermissions(value={"web:yjMahjongHallWaiters:add","web:yjMahjongHallWaiters:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(YjMahjongHallWaiters yjMahjongHallWaiters, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, yjMahjongHallWaiters)){
            return form(yjMahjongHallWaiters, model);
        }
        //新增或编辑表单保存
        boolean isDuplicate = checkDuplicate(yjMahjongHallWaiters);
        if (isDuplicate) {
            addMessage(model, "保存失败！服务生已存在！");
            return form(yjMahjongHallWaiters, model);
        }

        // 是否接收呼叫推送
        if ("on".equals(yjMahjongHallWaiters.getReceiveCallVal())) {
            yjMahjongHallWaiters.setReceiveCall(1);
        } else {
            yjMahjongHallWaiters.setReceiveCall(0);
        }

        // 上班状态
        if ("on".equals(yjMahjongHallWaiters.getWorkStateVal())) {
            yjMahjongHallWaiters.setWorkState(1);
        } else {
            yjMahjongHallWaiters.setWorkState(0);
        }

        yjMahjongHallWaitersService.save(yjMahjongHallWaiters);//保存
        addMessage(redirectAttributes, "保存棋牌室服务生成功");
        return "redirect:"+ Global.getAdminPath()+"/web/yjMahjongHallWaiters/?repage";
    }

    /**
     * 删除棋牌室服务生
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallWaiters:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(YjMahjongHallWaiters yjMahjongHallWaiters, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        yjMahjongHallWaitersService.delete(yjMahjongHallWaiters);
        j.setMsg("删除棋牌室服务生成功");
        return j;
    }

    /**
     * 批量删除棋牌室服务生
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallWaiters:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
//        for(String id : idArray){
//            yjMahjongHallWaitersService.delete(yjMahjongHallWaitersService.get(id));
//        }
        yjMahjongHallWaitersService.batchDeleteByLogic(Arrays.asList(idArray));
        j.setMsg("删除棋牌室服务生成功");
        return j;
    }

    /**
     * 微信端新建棋牌室服务生
     * @param yjMahjongHallWaiters
     * @return
     */
    @ApiOperation(notes = "createMahjongHallWaiters", httpMethod = "POST", value = "微信端新建棋牌室服务生")
    @ResponseBody
    @PostMapping(value = "createMahjongHallWaiters")
    public AjaxJson createMahjongHallWaiters(@RequestBody YjMahjongHallWaiters yjMahjongHallWaiters) {
        // 检查参数
        BeanValidators.validateWithException(validator, yjMahjongHallWaiters);

        AjaxJson j = new AjaxJson();

        // 特殊参数检查
        if (StringUtils.isBlank(yjMahjongHallWaiters.getOpenid())) {
            j.setSuccess(false);
            j.setMsg("用户不能为空!");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallWaiters.getSalesmanPhone())) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空!");
            return j;
        }

        if (yjMahjongHallWaiters.getMahjongHall() == null || StringUtils.isBlank(yjMahjongHallWaiters.getMahjongHall().getId())) {
            j.setSuccess(false);
            j.setMsg("棋牌室不能为空！");
            return j;
        }

        // 检查棋牌室是否存在
        String mahjongHallId = yjMahjongHallWaiters.getMahjongHall().getId();
        YjMahjongHall yjMahjongHall = yjMahjongHallService.get(mahjongHallId);
        if (yjMahjongHall == null) {
            j.setSuccess(false);
            j.setMsg("棋牌室不存在！");
            return j;
        }

        // 检查是否重复创建 棋牌室id-名称-手机号为联合主键
        boolean isDuplicate = checkDuplicate(yjMahjongHallWaiters);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("服务生已存在！");
            return j;
        }

        //新增或编辑表单保存
        yjMahjongHallWaiters.setCreateDate(new Date());
        yjMahjongHallWaitersService.save(yjMahjongHallWaiters);//保存

        j.setSuccess(true);
        j.setMsg("服务生创建成功！");
        j.getBody().put("data", yjMahjongHallWaiters);
        return j;
    }

    /**
     * 微信端获得棋牌室服务生信息
     * @return
     */
    @ApiOperation(notes = "getMahjongHallWaiterInfo", httpMethod = "GET", value = "微信端编辑棋牌室服务生信息")
    @ResponseBody
    @GetMapping(value = "getMahjongHallWaiterInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallWaiterId", value = "hallWaiterId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson getMahjongHallWaiterInfo(@NotBlank String hallWaiterId)
    {
        AjaxJson j = new AjaxJson();

        if (StringUtils.isBlank(hallWaiterId)) {
            j.setSuccess(false);
            j.setMsg("服务生id不能为空");
            return j;
        }

        YjMahjongHallWaiters yjMahjongHallWaiters = yjMahjongHallWaitersService.get(hallWaiterId);
        j.getBody().put("data", yjMahjongHallWaiters);
        return j;
    }

    /**
     * 微信端修改服务生信息
     * @param yjMahjongHallWaiters 棋牌室房间信息
     * @return
     */
    @ApiOperation(notes = "editMahjongHallWaiter", httpMethod = "PUT", value = "微信端修改棋牌室服务生")
    @ResponseBody
    @PutMapping(value = "editMahjongHallWaiter")
    public AjaxJson editMahjongHallWaiter(@RequestBody YjMahjongHallWaiters yjMahjongHallWaiters) {
        AjaxJson j = new AjaxJson();

        // 参数检查
        if (yjMahjongHallWaiters.getMahjongHall() == null || StringUtils.isBlank(yjMahjongHallWaiters.getMahjongHall().getId())) {
            j.setSuccess(false);
            j.setMsg("棋牌室id不能为空");
            return j;
        }

        // 检查棋牌室是否存在
        String mahjongHallId = yjMahjongHallWaiters.getMahjongHall().getId();
        YjMahjongHall yjMahjongHall = yjMahjongHallService.get(mahjongHallId);
        if (yjMahjongHall == null) {
            j.setSuccess(false);
            j.setMsg("棋牌室不存在！");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallWaiters.getId())) {
            j.setSuccess(false);
            j.setMsg("服务生id不能为空");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallWaiters.getName())) {
            j.setSuccess(false);
            j.setMsg("服务生名称不能为空");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallWaiters.getMobile())) {
            j.setSuccess(false);
            j.setMsg("服务生手机号不能为空");
            return j;
        }

        // 检查是否重复创建
        boolean isDuplicate = checkDuplicate(yjMahjongHallWaiters);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("服务生已存在");
            return j;
        }

        // 更新棋牌室房间信息
        yjMahjongHallWaitersService.save(yjMahjongHallWaiters);

        j.setSuccess(true);
        j.setMsg("更新成功");
        return j;
    }

    /**
     * 微信端删除棋牌室服务生
     * @return
     */
    @ApiOperation(notes = "deleteMahjongHallWaiters", httpMethod = "DELETE", value = "微信端删除棋牌室房间")
    @ResponseBody
    @DeleteMapping(value = "deleteMahjongHallWaiters")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallWaiterId", value = "hallWaiterId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson deleteMahjongHallWaiters(@NotBlank String hallWaiterId) {
        AjaxJson j = new AjaxJson();

        // 检查是否已经删除
        YjMahjongHallWaiters hallWaiters = yjMahjongHallWaitersService.get(hallWaiterId);
        if (hallWaiters == null || DataEntity.DEL_FLAG_DELETE.equals(hallWaiters.getDelFlag())) {
            j.setSuccess(false);
            j.setMsg("服务生已被其他人删除！");
            return j;
        }

        yjMahjongHallWaitersService.deleteWaiter(hallWaiterId);

        j.setMsg("删除服务生成功");
        return j;
    }

    /**
     * 服务生登录
     * @param yjPersonLogin 服务生登录实体类
     * @return
     */
    @ResponseBody
    @PostMapping(value = "login")
    public AjaxJson login(@Validated @RequestBody YjPersonLogin yjPersonLogin) throws Exception {
        AjaxJson j = new AjaxJson();

        // 直接检查token是否有效
        if (StringUtils.isNotBlank(yjPersonLogin.getToken())) {
            WxLoginModel loginModel = JwtTokenUtil.getAppLoginModel(yjPersonLogin.getToken());
            if (loginModel == null) {
                j.setSuccess(false);
                j.setMsg("token无效！");
                return j;
            }

            // 登录的类型不是业务员
            if (loginModel.getType() != WxLoginTypeEnum.WAITER) {
                j.setSuccess(false);
                j.setMsg("token无效！");
                return j;
            }

            YjMahjongHallWaitersLoginResponse response = new YjMahjongHallWaitersLoginResponse();
            response.setToken(yjPersonLogin.getToken());
            response.setHallIds(loginModel.getHallIds());

            j.getBody().put("data", response);

        } else {
            String phoneNumber = yjPersonLogin.getPhoneNumber();
            String captcha = yjPersonLogin.getCaptcha();

            if (StringUtils.isBlank(phoneNumber)) {
                j.setSuccess(false);
                j.setMsg("手机号不能为空");
                return j;
            }

            // 验证码校验
            if (StringUtils.isBlank(captcha)) {
                j.setSuccess(false);
                j.setMsg("验证码不能为空");
                return j;
            }

            // 检查验证码是否有效
            // 2021-06-18 追加测试用账号
            String testWaiterPhoneNumber = Global.getConfig("testWaiterPhoneNumber");
            String testWaiterCaptcha = Global.getConfig("testWaiterCaptcha");
            if (StringUtils.isNotBlank(testWaiterPhoneNumber) && phoneNumber.equals(testWaiterPhoneNumber))
            {
                if (!captcha.equals(testWaiterCaptcha)){
                    j.setSuccess(false);
                    j.setMsg("验证码无效");
                    return j;
                }
            } else {
                String redisCaptcha = redisUtil.get(RedisKeys.waiterLoginCaptcha(phoneNumber));
                if (StringUtils.isBlank(redisCaptcha)) {
                    j.setSuccess(false);
                    j.setMsg("验证码无效");
                    return j;
                }

                // 验证码不一致
                if (!captcha.equals(redisCaptcha)) {
                    j.setSuccess(false);
                    j.setMsg("验证码不正确");
                    return j;
                }
            }

            // 检查手机号是否有效
            YjMahjongHallWaiters record = new YjMahjongHallWaiters();
            record.setMobile(phoneNumber);

            List<YjMahjongHallWaiters> mahjongHallWaiters = yjMahjongHallWaitersService.findByMobile(phoneNumber);
            if (mahjongHallWaiters == null || mahjongHallWaiters.isEmpty()) {
                return new AjaxJson(false, "手机号不存在！");
            }

            String hallIds = mahjongHallWaiters.stream().map(p -> p.getMahjongHall().getId()).collect(Collectors.joining(","));

            // 设置token 有效期24小时
            // String token = Achieve.getUUIDString();
            // redisUtil.setEx(RedisKeys.waiterLoginToken(phoneNumber), token, 24 * 60 * 60, TimeUnit.SECONDS);
            String token = JwtTokenUtil.createToken(new WxLoginModel(phoneNumber, WxLoginTypeEnum.WAITER, hallIds));

            YjMahjongHallWaitersLoginResponse response = new YjMahjongHallWaitersLoginResponse();
            response.setToken(token);
            response.setHallIds(hallIds);

            j.getBody().put("data", response);
        }

        // 验证码一致，登录成功
        j.setSuccess(true);
        j.setMsg("登录成功");
        return j;
    }

    /**
     * 获得服务生的呼叫录音列表
     * @param yjRoomCalls
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping(value = "voicesList")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query",dataType = "string")})
    public AjaxJson voicesList(@RequestBody YjRoomCalls yjRoomCalls, HttpServletRequest request){
        AjaxJson j = new AjaxJson();

        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        if (yjRoomCalls == null) {
            yjRoomCalls = new YjRoomCalls();
        }

        List<YjRoomCalls> roomCallsList = new ArrayList<>();

        // 2021-05-19 检查当前服务生是否处于工作状态，如果处于不工作状态，则不能显示
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();
        List<YjMahjongHallWaiters> waitersList = yjMahjongHallWaitersService.findByMobile(phoneNumber);
        if (waitersList == null || waitersList.isEmpty())
        {
            j.setSuccess(false);
            j.setMsg("当前服务生不存在");
            j.getBody().put("data", roomCallsList);
            return j;
        }

//        YjMahjongHallWaiters waiter = waitersList.get(0);
//        Integer workState = waiter.getWorkState();
//        if (!new Integer(1).equals(workState)) { //不在工作，则不返回呼叫列表
//            j.getBody().put("data", roomCallsList);
//            return j;
//        }

        // 2021-05-21 逻辑变更：显示已经接收过的呼叫请求信息
        yjRoomCalls.setPhoneNumber(phoneNumber);
        roomCallsList = yjRoomCallsService.getWaiterRoomCalls(yjRoomCalls);
        j.getBody().put("data", roomCallsList);
        return j;
    }

    /**
     * 响应呼叫
     * @param yjRoomCalls
     * @param request
     * @return
     */
    @ResponseBody
    @PutMapping(value = "responseCall")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query",dataType = "string")})
    public AjaxJson responseCall(@RequestBody YjRoomCalls yjRoomCalls, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        if (yjRoomCalls == null || StringUtils.isBlank(yjRoomCalls.getId())) {
            j.setSuccess(false);
            j.setMsg("呼叫id不能为空！");
            return j;
        }

        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 设置token内的phoneNumber
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();
        yjRoomCalls.setPhoneNumber(phoneNumber);

        // 响应呼叫
        yjRoomCalls.setResponsedBy(phoneNumber);
        yjRoomCallsService.responseRoomCall(yjRoomCalls);

        // 删除redis key，避免再次呼叫
        String redisKey = CALL_PUSH_REDIS_PREFIX + yjRoomCalls.getId();
        redisUtil.delete(redisKey);

        j.setSuccess(true);
        j.setMsg("响应呼叫成功！");
        return j;
    }

    /**
     * 完成呼叫
     * @param yjRoomCalls
     * @param request
     * @return
     */
    @ResponseBody
    @PutMapping(value = "completeCall")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query",dataType = "string")})
    public AjaxJson completeCall(@RequestBody YjRoomCalls yjRoomCalls, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        if (yjRoomCalls == null || StringUtils.isBlank(yjRoomCalls.getId())) {
            j.setSuccess(false);
            j.setMsg("呼叫id不能为空！");
            return j;
        }

        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 设置token内的phoneNumber
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();
        yjRoomCalls.setPhoneNumber(phoneNumber);

        // 完成呼叫
        yjRoomCalls.setCompletedBy(phoneNumber);
        yjRoomCallsService.completeRoomCall(yjRoomCalls);

        // 删除redis key，避免再次呼叫
        String redisKey = CALL_PUSH_REDIS_PREFIX + yjRoomCalls.getId();
        redisUtil.delete(redisKey);

        j.setSuccess(true);
        j.setMsg("完成呼叫成功！");
        return j;
    }

    /**
     * 上传头像
     * @param imageModel 图片model
     * @param request 请求
     * @return
     */
    @ResponseBody
    @PostMapping(value = "uploadAvatar")
    public AjaxJson uploadAvatar(@RequestBody WxImageModel imageModel, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        // 校验token
        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 检查上传imageModel的信息
        String base64Data = imageModel.getBase64Data();
        if (StringUtils.isBlank(base64Data)) {
            j.setSuccess(false);
            j.setMsg("文件数据不能为空");
            return j;
        }

        // 检查图片格式
        String extOfFile = com.jeeplus.common.utils.image.ImageUtil.checkImageBase64Format(base64Data);
        if (StringUtils.isBlank(extOfFile)) {
            j.setSuccess(false);
            j.setMsg("图片格式不正确");
            return j;
        }

        // 将base64Data转化为图片
        String imageFilename = saveImage(base64Data, extOfFile);
        if (StringUtils.isBlank(imageFilename)) {
            j.setSuccess(false);
            j.setMsg("文件不能被正常保存");
            return j;
        }

        // 设置token内的phoneNumber
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();

        // 保存头像地址
        String imagePath = Global.getConfig("imgUrl") + imageFilename;

        YjMahjongHallWaiters record = new YjMahjongHallWaiters();
        record.setMobile(phoneNumber);
        record.setAvatar(imagePath);
        yjMahjongHallWaitersService.updateByMobile(record);

        j.setSuccess(true);
        j.setMsg("上传头像成功！");
        j.getBody().put("data", imagePath);
        return j;
    }

    /**
     * android端设置服务生属性
     * 目前支持设置 头像、是否接收语音推送receiveCall、上班状态workState
     * @param yjMahjongHallWaiters
     * @param request
     * @return
     */
    @ResponseBody
    @PutMapping(value = "updateMahjongHallWaiter")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query",dataType = "string")})
    public AjaxJson updateMahjongHallWaiter(@RequestBody YjMahjongHallWaiters yjMahjongHallWaiters, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        if (yjMahjongHallWaiters == null) {
            j.setSuccess(false);
            j.setMsg("参数不能为空！");
            return j;
        }

        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 设置token内的phoneNumber
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();
        yjMahjongHallWaiters.setMobile(phoneNumber);

        // 设置属性
        yjMahjongHallWaitersService.updateByMobile(yjMahjongHallWaiters);

        j.setSuccess(true);
        j.setMsg("服务生更新成功！");
        return j;
    }

    /**
     * android端获取服务生信息
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping(value = "getAndroidMahjongHallWaiterInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query",dataType = "string")})
    public AjaxJson getAndroidMahjongHallWaiterInfo(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        AjaxJson checkResult = checkToken(request);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 设置token内的phoneNumber
        String phoneNumber = checkResult.getBody().get(PHONE_NUMBER).toString();
        List<YjMahjongHallWaiters> list = yjMahjongHallWaitersService.findByMobile(phoneNumber);
        if (list == null && list.isEmpty()) {
            j.setSuccess(false);
            j.setMsg("服务生信息不存在");
            return j;
        }

        j.setSuccess(true);
        j.setMsg("获得服务生信息成功");
        j.getBody().put("data", list.get(0));
        return j;
    }

    /**
     * 校验token
     * @param request
     * @return
     */
    private AjaxJson checkToken(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        // authorization
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            return new AjaxJson(false, "token不能为空！");
        }

        WxLoginModel loginModel = JwtTokenUtil.getAppLoginModel(authorization);
        if (loginModel == null) {
            return new AjaxJson(false, "token无效！");
        }

        String phoneNumber = loginModel.getPhoneNumber();
        if (!phoneNumber.equals(phoneNumber)) {
            return new AjaxJson(false, "当前登录账号手机号无效！");
        }

        if (WxLoginTypeEnum.WAITER != loginModel.getType()) {
            return new AjaxJson(false, "当前登录账号不是服务生！");
        }

        j.getBody().put(PHONE_NUMBER, loginModel.getPhoneNumber());
        return j;
    }

    /**
     * 检查是否重复
     * @param yjMahjongHallWaiters
     * @return
     */
    private boolean checkDuplicate(YjMahjongHallWaiters yjMahjongHallWaiters) {
        YjMahjongHallWaiters record = new YjMahjongHallWaiters(yjMahjongHallWaiters.getMahjongHall().getId(), yjMahjongHallWaiters.getName(), yjMahjongHallWaiters.getMobile());
        if (StringUtils.isNotBlank(yjMahjongHallWaiters.getId())) {
            record.setId(yjMahjongHallWaiters.getId());
        }

        return yjMahjongHallWaitersService.isDuplicate(record);
    }

    /**
     * 保存图片
     * @param base64Data
     * @return
     */
    private String saveImage(String base64Data, String extOfFile) {
        String filename = null;
        try {
            String imageDirPath = Global.getConfig("imgFilesDirPath");
            File dir = new File(imageDirPath);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }

            filename = Achieve.getUUIDString() + "." + extOfFile;

            Path filePath = Paths.get(imageDirPath, filename);
            String destFilePath = filePath.toString();
            ImageUtil.convertBase64DataToImage(base64Data, destFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            filename = null;
        }

        return filename;
    }
}
